package com.idbk.chargestation.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

/**
 * 历史搜索 数据库接口
 * @author lupc
 *
 */
public class SearchHistoryDatabase {

	private final DBHelper dbHelper;

	public SearchHistoryDatabase(Context context) {
		dbHelper = new DBHelper(context);
	}

	/**
	 * 插入
	 */
	public void insert(String keyword) {
		final String sql = "replace into " + DBHelper.TABLE_NAME_SEARCH_HISTORY
				+ " (keyword)"
				+ " values(?);";
		SQLiteDatabase sqlite = dbHelper.getWritableDatabase();
		sqlite.execSQL(
				sql,
				new String[]{keyword});
		sqlite.close();
	}

	/**
	 * 删除全部
	 */
	public void deleteAll() {
		final String sql = "delete from " + DBHelper.TABLE_NAME_SEARCH_HISTORY + ";";
		SQLiteDatabase sqlite = dbHelper.getWritableDatabase();
		sqlite.execSQL(sql);
		sqlite.close();
	}

	/**
	 * 删除单条
	 * @param id id
	 */
	public void deleteOne(int id) {
		final String sql = "delete from " + DBHelper.TABLE_NAME_SEARCH_HISTORY + " where id=?";
		SQLiteDatabase sqlite = dbHelper.getWritableDatabase();
		sqlite.execSQL(
				sql,
				new String[]{id + ""});
		sqlite.close();
	}


	public List<KeywordItem> select(int pageIndex,int pageSize) {
		int offset = (pageIndex -1) * pageSize;
		List<KeywordItem> data =  new ArrayList<KeywordItem>();
		SQLiteDatabase sqlite = dbHelper.getReadableDatabase();
		Cursor cursor = sqlite.rawQuery(
				"select * from " + DBHelper.TABLE_NAME_SEARCH_HISTORY +
				" order by id desc limit ? offset ? ;",
				new String[]{
						pageSize + "",
						offset + "" });
		fillData(data,cursor);
		sqlite.close();	

		return data;
	}

	private void fillData(List<KeywordItem> data,Cursor cursor) {
		for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
			KeywordItem item = new KeywordItem();
			item.id = cursor.getInt(0);
			item.keyword = cursor.getString(1);
			data.add(item);
		}
		if(!cursor.isClosed()) {
			cursor.close();
		}
	}

	public void close() {
		dbHelper.close();
	}

	public static class KeywordItem{
		public int id;
		public String keyword;
	}
	
}
